var GAMESTATES = {PLACINGPHASE: 0, PLAYER1MOVE: 1, PLAYER2MOVE: 2, PLAYER1WIN: 3, PLAYER2WIN: 4};
var requesterID;

$(document).ready(function () {

    requestGameState();
    requesterID = setInterval(requestGameState, 5000);

});

function requestGameState() {

    $.ajax({
        type: "POST",
        url: "/requestGameState",
        cache: false,
        timeout: 5000,

        success: function (data) {

            if (typeof data.error == 'undefined') {

                var response = JSON.parse(data.response);

                var i = 0;

                for (var player in response) {

                    i++;
                    $(".player" + i).html(player);
                    updateShips("#gameboard-p" + i, response[player].ships);

                }

                for (var player in response) {

                    updateShots("#gameboard-p" + i, response[player].hits, response[player].misses);
                    i--;

                }

                var state = JSON.parse(data.state);

                if (state == GAMESTATES.PLAYER1MOVE) {

                    $(".player1").css("border", "double");
                    $(".player2").css("border", "none");

                } else if (state == GAMESTATES.PLAYER2MOVE) {

                    $(".player2").css("border", "double");
                    $(".player1").css("border", "none");

                } else if (state == GAMESTATES.PLAYER1WIN) {

                    $("#message").html("<div id='serverOkMessage'><p>Player " + $(".player1").html() + " Wins!</p></div>");
                    clearInterval(requesterID);

                } else if (state == GAMESTATES.PLAYER2WIN) {

                    $("#message").html("<div id='serverOkMessage'><p>Player " + $(".player2").html() + " Wins!</p></div>");
                    clearInterval(requesterID);

                }

            } else {

                $("#message").html("<div id='serverWarningMessage'><p>" + data.error + "</p></div>");
                clearMessage(3000);
                return false;

            }

        }, error: function (jqXHR, textStatus, errorThrown) {

            $("#message").html("<div id='serverErrorMessage'><p>" + 'error ' + textStatus + " " + errorThrown + "</p></div>");
            clearMessage(3000);

        }
    });
}

function clearMessage(delay) {

    setTimeout(function () {

        $("#message").html("");

    }, delay);
}


